package com.pp.demo.security;

import com.pp.demo.module.auth.service.CustomUserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final SecurityProperties securityProperties;
    // 注入自定义的UserDetailsService
    private final CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers(securityProperties.getExcluded().toArray(new String[0]));
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                // 基于 token，不需要使用 Session 了
                .sessionManagement() // Session 管理
                // 管理 Session 创建策略
                //    ALWAYS, 总是创建HttpSession
                //    NEVER, 只会在需要时创建一个HttpSession
                //    IF_REQUIRED, 不会创建HttpSession，但如果它已经存在，将可以使用HttpSession
                //    STATELESS; 永远不会创建HttpSession，它不会使用HttpSession来获取SecurityContext
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests() // 授权请求
                // 使用处理后的路径列表
                .antMatchers(securityProperties.getProcessedExcludedPaths().toArray(new String[0]))
                .permitAll()
                // 除了上面的请求，其他所有请求都需要认证
                .anyRequest()
                .authenticated()
                .and()
                // 禁止缓存
                .headers()
                .cacheControl();

        // 自定义拦截器 JWT 过滤器
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        // 可选：添加跨域配置
//        http.cors();
    }

    // 配置认证提供者
//    @Bean
//    public UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withUsername("systemA")
//                .password(passwordEncoder().encode("password123"))
//                .authorities("SYSTEM_A")
//                .build());
//        manager.createUser(User.withUsername("systemB")
//                .password(passwordEncoder().encode("password123"))
//                .authorities("SYSTEM_B")
//                .build());
//        return manager;
//    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
